#!/bin/bash
# SchedulerAI Backend Health Check Script

set -e

# Configuration
HEALTH_ENDPOINT="http://localhost:${API_PORT:-8000}/health"
TIMEOUT=10
MAX_RETRIES=3

# Function to check health endpoint
check_health() {
    local attempt=$1
    echo "Health check attempt $attempt/$MAX_RETRIES..."
    
    # Use curl if available, otherwise use wget
    if command -v curl >/dev/null 2>&1; then
        response=$(curl -s -f --max-time $TIMEOUT "$HEALTH_ENDPOINT" 2>/dev/null) || return 1
    elif command -v wget >/dev/null 2>&1; then
        response=$(wget -q -T $TIMEOUT -O - "$HEALTH_ENDPOINT" 2>/dev/null) || return 1
    else
        # Fallback to Python
        response=$(python -c "
import urllib.request
import json
import socket
socket.setdefaulttimeout($TIMEOUT)
try:
    with urllib.request.urlopen('$HEALTH_ENDPOINT') as response:
        print(response.read().decode())
except Exception as e:
    exit(1)
" 2>/dev/null) || return 1
    fi
    
    # Check if response contains expected health status
    if echo "$response" | grep -q '"status".*"healthy"'; then
        echo "Health check passed: Service is healthy"
        return 0
    else
        echo "Health check failed: Unexpected response format"
        echo "Response: $response"
        return 1
    fi
}

# Function to check basic service availability
check_port() {
    local port=${API_PORT:-8000}
    echo "Checking if port $port is listening..."
    
    if command -v netstat >/dev/null 2>&1; then
        netstat -tuln | grep -q ":$port " && return 0
    elif command -v ss >/dev/null 2>&1; then
        ss -tuln | grep -q ":$port " && return 0
    else
        # Fallback to Python socket check
        python -c "
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
result = sock.connect_ex(('localhost', $port))
sock.close()
exit(0 if result == 0 else 1)
" && return 0
    fi
    
    return 1
}

# Main health check logic
main() {
    echo "Starting health check for SchedulerAI Backend..."
    echo "Timestamp: $(date)"
    echo "Health endpoint: $HEALTH_ENDPOINT"
    
    # First check if the port is listening
    if ! check_port; then
        echo "FAILED: Service port is not listening"
        exit 1
    fi
    
    # Try health endpoint multiple times
    for i in $(seq 1 $MAX_RETRIES); do
        if check_health $i; then
            echo "SUCCESS: Health check passed"
            exit 0
        fi
        
        if [ $i -lt $MAX_RETRIES ]; then
            echo "Retrying in 2 seconds..."
            sleep 2
        fi
    done
    
    echo "FAILED: Health check failed after $MAX_RETRIES attempts"
    exit 1
}

# Run main function
main "$@"